import datetime
from utils import cleanhtml
import os 
import requests

class ChanPost:
    def __init__(self, postData=None):
        if postData:
            self.image_data = []
            self.ext_data = []
            self.tim = []
            self.postData = postData
            self.postNumber = postData["no"]
            self.comment = postData["com"] if "com" in postData else "none"
            self.name = postData["name"] if "name" in postData else "none"
            self.time = postData["time"]
            self.reply_to = postData["resto"]
           
            if "filename" in postData:
                self.image_data.append(postData["filename"])
                self.ext_data.append(postData["ext"])
                self.tim.append(postData["tim"])

            if "extra_files" in postData:
                for i in postData["extra_files"]:
                    if "filename" in i and "ext" in i and "tim" in i:
                        self.image_data.append(i["filename"])
                        self.ext_data.append(i["ext"])
                        self.tim.append(i["tim"])

    def __str__(self):
        return (
            "=== "
            + str(self.isOP())
            + " ===\nName:"
            + str(self.name)
            + "\nPostNumber:"
            + str(self.postNumber)
            + "\nTime:"
            + str(self.postTime(human=True))
            + "\nCommentLength:"
            + str(len(cleanhtml(self.comment)))
            + "\nFiles"
            + str(self.getFileNames())
        )
    def __len__(self):
        return len(cleanhtml(self.comment))

    def isOP(self):
        if self.reply_to > 0:
            return "reply"
        else:
            return "OP"

    def getFileNames(self):
        retar = []

        if len(self.image_data) != len(self.ext_data):
            return "DATA ERROR IN POST(probably due to save/load functions)" + str(
                self.image_data + self.ext_data
            )
        for i, _tfile in enumerate(self.image_data):
            retar.append(self.image_data[i] + self.ext_data[i])
        return retar

    def getFileLinks(self):
        retar = []

        if len(self.tim) != len(self.ext_data):
            return "DATA ERROR IN POST(probably due to save/load functions)" + str(
                self.tim + self.ext_data
            )
        for i, _tfile in enumerate(self.tim):
            if len(self.tim[i]) > 0:
                retar.append(self.tim[i] + self.ext_data[i])
        return retar

    def getExtAsString(self):
        return "{sp35i4l}".join(self.ext_data)

    def getImageNameAsString(self):
        return "{sp35i4l}".join(self.image_data)

    def getTimAsString(self):
        return "{sp35i4l}".join(self.tim)

    def parseExtAsString(self, data):
        self.ext_data = data.split("{sp35i4l}")

    def parseImageNameAsString(self, data):
        self.image_data = data.split("{sp35i4l}")

    def parseTimAsString(self, data):
        self.tim = data.split("{sp35i4l}")

    def postTime(self, human=False):
        months = [
            "January", 
            "February",
            "March", 
            "April", 
            "May", 
            "June",
            "July", 
            "August", 	
            "September",
            "October", 
            "November", 	
            "December",
        ]
        if human:
            rdate = datetime.datetime.utcfromtimestamp(self.time)
            return f" {rdate.year} {months[rdate.month-1]} {rdate.day}"
        else: 
            return self.time
    
    def year(self):
        rdate = datetime.datetime.utcfromtimestamp(self.time)
        return rdate.year

    def month(self):
        rdate = datetime.datetime.utcfromtimestamp(self.time)
        return rdate.month

    def day(self):
        rdate = datetime.datetime.utcfromtimestamp(self.time)
        return rdate.day

    def hour(self):
        rdate = datetime.datetime.utcfromtimestamp(self.time)
        return rdate.hour
    
    def minute(self):
        rdate = datetime.datetime.utcfromtimestamp(self.time)
        return rdate.minute
    
    def getText(self):
        return cleanhtml(self.comment)

    def __downloadFiles__(self, board, ext_type):
        fileDir = os.path.expanduser('~/.meme_magic_stats/files')

        def networkdl(link,name):
            r = requests.get(link)
       
            if r.status_code == 200:
                with open(fileDir+"/"+name, "wb") as f:
                    f.write(r.content)
            else:
                return -1
            return 0

        # if file directory does not exist, create it
        if not os.path.exists(fileDir):
            os.makedirs(fileDir)

        # iterate over all posts
        for i, _tfile in enumerate(self.tim):
            if len(self.tim[i]) > 0 and self.ext_data[i] == ext_type:
                link = self.tim[i] + self.ext_data[i]
                print("Downloading: "+self.image_data[i])
                if len(link) > 64:     
                    dl_link = "https://media.8ch.net/file_store/"+link
                    networkdl(dl_link, link)
                else:
                    dl_link = "https://media.8ch.net"+board+"src/"+link
                    networkdl(dl_link, link)